import 'dart:convert';

import 'package:flutter/foundation.dart';
// import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
// import 'package:native_widgets/native_widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
// import 'package:http/http.dart' as http;
import 'package:nanoid/nanoid.dart';

import '../../constants/common.dart';
import 'worker.dart';

class AuthModel with ChangeNotifier {
  String errorMessage = "";

  bool _rememberMe = false;
  bool _stayLoggedIn = true;
  bool _useBio = false;
  Worker? _worker;

  bool get rememberMe => _rememberMe;

  void handleRememberMe(bool value) {
    _rememberMe = value;
    notifyListeners();
    SharedPreferences.getInstance().then((prefs) {
      prefs.setBool("remember_me", value);
    });
  }

  bool get isBioSetup => _useBio;

  void handleIsBioSetup(bool value) {
    _useBio = value;
    notifyListeners();
    SharedPreferences.getInstance().then((prefs) {
      prefs.setBool("use_bio", value);
    });
  }

  bool get stayLoggedIn => _stayLoggedIn;

  void handleStayLoggedIn(bool value) {
    _stayLoggedIn = value;
    notifyListeners();
    SharedPreferences.getInstance().then((prefs) {
      prefs.setBool("stay_logged_in", value);
    });
  }

  void loadSettings() async {
    var _prefs = await SharedPreferences.getInstance();
    try {
      _useBio = _prefs.getBool("use_bio") ?? false;
    } catch (e) {
      print(e);
      _useBio = false;
    }
    try {
      _rememberMe = _prefs.getBool("remember_me") ?? false;
    } catch (e) {
      print(e);
      _rememberMe = false;
    }
    try {
      _stayLoggedIn = _prefs.getBool("stay_logged_in") ?? false;
    } catch (e) {
      print(e);
      _stayLoggedIn = false;
    }

    if (_stayLoggedIn) {
      Worker? _savedWorker;
      try {
        String? _saved = _prefs.getString("worker_data");
        print("Saved: $_saved");
        _savedWorker = Worker.fromJson(json.decode(_saved!));
      } catch (e) {
        print("Worker Not Found: $e");
      }
      if (!kIsWeb && _useBio) {
        if (await biometrics()) {
          _worker = _savedWorker;
        }
      } else {
        _worker = _savedWorker;
      }
    }
    notifyListeners();
  }

  Future<bool> biometrics() async {
    final LocalAuthentication auth = LocalAuthentication();
    bool authenticated = false;
    try {
      authenticated = await auth.authenticate(
          localizedReason: 'Scan your fingerprint to authenticate',
          options: const AuthenticationOptions(
              useErrorDialogs: true, stickyAuth: false));
    } catch (e) {
      print(e);
    }
    return authenticated;
  }

  Worker? get worker => _worker;

  // Future<Worker?> getInfo(String token) async {
  //   try {
  //     var _data = await http.get(Uri.parse(apiURL + '/info'));
  //     // var _json = json.decode(json.encode(_data));
  //     var _newWorker = Worker.fromJson(json.decode(_data.body)["data"]);
  //     _newWorker?.token = token;
  //     return _newWorker;
  //   } catch (e) {
  //     print("Could Not Load Data: $e");
  //     return null;
  //   }
  // }

  Future<bool> login({
    required String mobile,
    required String password,
  }) async {
    var randomNanoid = nanoid(10);
    String _mobile = mobile;
    String _password = password;

    // TODO: API LOGIN CODE HERE
    await Future.delayed(Duration(seconds: 3));
    print("Logging In => $_mobile, $_password");

    if (_rememberMe) {
      SharedPreferences.getInstance().then((prefs) {
        prefs.setString("saved_mobile", _mobile);
      });
    }

    var loginRes = await login(mobile: mobile, password: password);
    print(loginRes);

    // Get Info For Worker
    // Worker? _newWorker = await getInfo(randomNanoid.toString());
    // if (_newWorker != null) {
    //   _worker = _newWorker;
    //   notifyListeners();

    //   SharedPreferences.getInstance().then((prefs) {
    //     var _save = json.encode(_worker!.toJson());
    //     print("Data: $_save");
    //     prefs.setString("user_data", _save);
    //   });
    // }

    // if (_newWorker?.token == null || _newWorker!.token.isEmpty) return false;
    return true;
  }

  Future<void> logout() async {
    _worker = null;
    notifyListeners();
    SharedPreferences.getInstance().then((prefs) {
      // prefs.setString("user_data", null);
    });
    return;
  }
}
